﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Domain.Setup.Entities
{
    /// <summary>
    /// Location is a physical location that can be used for the purposes of conducting studies.
    /// </summary>
    public class Location : ICloneable
    {
        private List<TransitTime> _TransitTimes;

        /// <summary>
        /// Gets the unique location id.
        /// </summary>
        public int Id { get; private set; }

        /// <summary>
        /// The name of the location.
        /// </summary>
        /// <value>
        /// The name.
        /// </value>                
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the locations description.
        /// </summary>
        /// <value>
        /// The description.
        /// </value>
        public string Description { get; set; }


        /// <summary>
        /// Gets list of transit times from this location to other locations.
        /// </summary>
        public IEnumerable<TransitTime> TransitTimes
        {
            get
            {
                // Return a copy of the private list so that external classes cannot alter the list.
                return _TransitTimes.Clone();
            }
            private set
            {
                _TransitTimes = new List<TransitTime>(value);
            }
        }

        /// <summary>
        /// Adds the a transit time from this location to another.
        /// </summary>
        /// <param name="transitTime">The transit time.</param>
        public void AddTransitTime(TransitTime transitTime)
        {
            this._TransitTimes.Add(transitTime);
        }

        /// <summary>
        /// Gets the transit time from this location to another location.
        /// </summary>
        /// <param name="location">The location.</param>
        /// <returns></returns>
        public TransitTime GetTransitTimeToLocation(Location location)
        {
            // Find a transit time to the specified location in the configured transit times.
            var transitTime = (from t in _TransitTimes
                               where t.ToLocation.Id == location.Id
                               select t).FirstOrDefault();

            return transitTime;
        }

        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        /// A new object that is a copy of this instance.
        /// </returns>
        public object Clone()
        {
            return new Location
            {
                Description = this.Description,
                Id = this.Id,
                Name = this.Name,
                _TransitTimes = new List<TransitTime>(this._TransitTimes.Clone())
            };
        }
    }
}
